package com.zhou.springbootz08;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 发邮件
 * @author zhoudong
 */
@RestController
public class IndexController {
    private Logger log = LoggerFactory.getLogger(getClass()); // 日志

    @Resource
    private JavaMailSender jms;
    @Value("${spring.mail.username}")
    private String formUser;

    @ApiOperation(value = "发送短信接口", notes = "发送短信接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "发送地址", required = true),
            @ApiImplicitParam(name = "title", value = "发送标题", required = true),
            @ApiImplicitParam(name = "content", value = "发送内容", required = true)
    })
    @GetMapping("/send")
    public Map send(@RequestParam String email,@RequestParam String title,@RequestParam String content){
        try{
            sendMail(email,title,content);
            return Map.of("msg","success");
        }catch (Exception e){
            return Map.of("msg","fail");
        }

    }

    /**
     * 发邮件
     * @param toEmail
     * @param title
     * @param content
     */
    private void sendMail(String toEmail,String title,String content){
        var mainMessage = new SimpleMailMessage();	//建立邮件连接
        mainMessage.setFrom(formUser);				//发送者
        mainMessage.setTo(toEmail);					//接收者
        mainMessage.setSubject(title);				//发送的标题
        mainMessage.setText(content);				//发送的内容
        log.info("线程：{}【发送邮件内容】：{}", Thread.currentThread().getName(), JSON.toJSONString(mainMessage));
        jms.send(mainMessage);
    }
}
